package com.lagou.service;

import com.lagou.pojo.DataBaseEntity;
import com.lagou.zkClient.ZkClientFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.curator.framework.CuratorFramework;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author
 */
public class DataSourceBuilder {

    private static ComboPooledDataSource dataSource;

    private static CuratorFramework zkClient = ZkClientFactory.getZkClient();

    public static void build() throws Exception {
        DataBaseEntity dataBaseEntity = new DataBaseEntity();
        if(zkClient.checkExists().forPath(ZkConfigService.DATABASE_CONFIG) == null){
            System.out.println("请先调用/config，在zookeeper中设置数据源参数！");
            zkClient.create().forPath(ZkConfigService.DATABASE_CONFIG);
        }
        List<String> childrenList = zkClient.getChildren().forPath(ZkConfigService.DATABASE_CONFIG);
        if(childrenList.size() == 0){
            System.out.println("请先调用/config，在zookeeper中设置数据源参数！");
            return;
        }

        for (String children : childrenList) {
            byte[] bytes = zkClient.getData().forPath(ZkConfigService.DATABASE_CONFIG + "/" + children);
            String data = new String(bytes);
            Field declaredField = DataBaseEntity.class.getDeclaredField(children);
            declaredField.setAccessible(true);
            declaredField.set(dataBaseEntity, data);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(dataBaseEntity.getDriverClassName());
        comboPooledDataSource.setJdbcUrl(dataBaseEntity.getJdbcUrl());
        comboPooledDataSource.setUser(dataBaseEntity.getUsername());
        comboPooledDataSource.setPassword(dataBaseEntity.getPassword());
        if(dataSource == null){
            dataSource = comboPooledDataSource;
        } else {
            //关闭之前的链接
            dataSource.close();
            dataSource = comboPooledDataSource;
        }
    }

    public static ComboPooledDataSource getDataSource() {
        return dataSource;
    }

    public static void destroyDataSource() {
        if(DataSourceBuilder.dataSource != null){
            DataSourceBuilder.dataSource.close();
            DataSourceBuilder.dataSource = null;
        }
    }
}
